package org.apache.mina.example.lily;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.http.DecoderState;
import org.apache.mina.http.HttpRequestImpl;
import org.apache.mina.http.api.HttpEndOfContent;
import org.apache.mina.http.api.HttpMethod;
import org.apache.mina.http.api.HttpRequest;
import org.apache.mina.http.api.HttpVersion;

public class HttpRequestHandler extends IoHandlerAdapter{
	
	private HttpRequest request;
	int i=0;

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		HttpVersion version=HttpVersion.HTTP_1_1;
    	HttpMethod method =HttpMethod.GET;
    	String requestedPath = "/MsgrReceiver";
    	String queryString = "signature=fe99b2962341fcc246aee89000c49afe8f7fb9f9&timestamp=1366703582&nonce=1367";
    	Map<String ,String > headers= new HashMap<String, String>();
    	headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    	headers.put("Connection", "close");
    	headers.put("Host", "wechat.yihaodian.com");
        request = new HttpRequestImpl(version, method, requestedPath, queryString, headers);
    	session.write(request);
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		DecoderState state = (DecoderState)session.getAttribute("http.ds");
		String body = "";
//		switch(state){
//			case NEW:
//			case HEAD:break;
//			case BODY:{
//			};break;
//			default :session.close(true);
//		}
		body =((IoBuffer)message).getString(Charset.forName("UTF-8").newDecoder());
		System.out.println(i++);
		System.out.println(body);
		
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
}
